package io.renren.controller;


import io.renren.annotation.Login;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.SmsEntity;
import io.renren.entity.UserEntity;
import io.renren.form.RegisterForm;
import io.renren.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * 注册接口
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 17:27
 */
@RestController
@RequestMapping("/api")
@Api(tags="注册接口")
public class ApiRegisterController {
    @Autowired
    private UserService userService;

    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@RequestBody RegisterForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        UserEntity user = new UserEntity();
        user.setMobile(form.getMobile());
        user.setUsername(form.getMobile());
        user.setPassword(DigestUtils.sha256Hex(form.getPassword()));
        user.setCreateTime(new Date());
        userService.insert(user);

        return R.ok();
    }
    /**
     * 发送验证码
     */
    @Login
    @PostMapping("sendYanZhengMa")
    @ApiOperation("发送验证码")
    public R sendYanZhengMa(@RequestBody Map mobile){
        userService.sendSms((String) mobile.get("mobile"));
        return R.ok("验证码发送成功",100);
    }

    /**
     * 发送验证码
     */
    @Login
    @PostMapping("initUser")
    @ApiOperation("初始化用户数据")
    public R updateUser(@RequestBody Map mobile,@RequestAttribute("userId") Long userId){
        //验证验证码
        SmsEntity s=userService.getSmsEntityByCode(new SmsEntity(((String) mobile.get("phoneNumber")),((String) mobile.get("code"))));
        if(s==null){
            return R.ok("验证码不正确或者超时",101);
        }else{
            //userService.sendSms((String) mobile.get("mobile"));
            UserEntity userEntity=new UserEntity();
            userEntity.setUserId(userId);
            userEntity.setMobile(((String) mobile.get("phoneNumber")));
            userEntity.setScore((Float.parseFloat((String) mobile.get("score"))));
            userEntity.setNickName(((String) mobile.get("username")));
            userEntity.setWenlike(((String) mobile.get("wenlike")));
            userService.updateById(userEntity);
            return R.ok("修改成功",100);
        }


    }

}
